import { v4 as uuidv4 } from 'uuid';
import { payLogicProjectKey } from 'src/config/pay';
const crypto = require('crypto');

export function genTransactionId() {
    const now = new Date();
    const offset = 8 * 60 * 60 * 1000;
    const beijingTime = new Date(now.getTime() + offset);
    const timeStr = beijingTime.toISOString().replace(/[-:.TZ]/g, '').slice(0, 12);
    const randomStr = uuidv4().replace(/-/g, '');
    return `${timeStr}_${randomStr}`;
}

export function genPayLogicSign(data) {
    const validData = {};  // 去除参数值为空的参数
    for (const [key, value] of Object.entries(data)) {
        if (value !== null && value !== "") {
            validData[key] = value;
        }
    }

    const dataString = Object.keys(validData)
        .sort()
        .map(key => `${key}=${validData[key]}`)
        .join('&');

    const hash = crypto.createHash('sha256');
    hash.update(payLogicProjectKey + dataString, 'utf8');
    const sign = hash.digest('hex');

    return sign;
}

export function convertTimestampToDatetimeFormat(timestamp: number): string {
    // 如果时间戳是 10 位，乘以 1000 转换为 13 位
    const millisecondsTimestamp = timestamp.toString().length === 10
        ? timestamp * 1000
        : timestamp;

    // 创建一个 Date 对象
    const date = new Date(millisecondsTimestamp);

    // 将时间调整为北京时间 （UTC+8）
    const beijingOffset = 8 * 60; // 北京时间偏移量为 8 小时，单位为分钟
    const utcTimestamp = date.getTime() + (beijingOffset * 60 * 1000);
    const beijingDate = new Date(utcTimestamp);

    // 格式化为 'YYYY-MM-DD HH:mm:ss' 格式
    const year = beijingDate.getFullYear();
    const month = String(beijingDate.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始
    const day = String(beijingDate.getDate()).padStart(2, '0');
    const hours = String(beijingDate.getHours()).padStart(2, '0');
    const minutes = String(beijingDate.getMinutes()).padStart(2, '0');
    const seconds = String(beijingDate.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export function generateDefaultUserName() {
    // 返回 “泡泡” + 随机的四位大写字母或数字字符串
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let userNameSuffix = '';
    for (let i = 0; i < 4; i++) {
        userNameSuffix += chars[Math.floor(Math.random() * chars.length)];
    }
    const userName = '恋恋' + userNameSuffix;
    return userName;
}
